package com.jcvision.mms.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jcvision.mms.dao.FrameDao;
import com.jcvision.mms.dao.MmsDao;
import com.jcvision.mms.model.Frame;
import com.jcvision.mms.model.FrameExample;
import com.jcvision.mms.model.Mms;
import com.jcvision.mms.util.Constant;
import com.jcvision.mms.util.ErrorMsg;

@Controller
@RequestMapping("/module/frame")
public class FrameController extends BaseController {

	/**
	 * 转到帧添加页面
	 * @param mmsId
	 * @param map
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/toAdd.do")
	public String toAdd(Long mmsId, ModelMap map){
		if(mmsId == null){
			map.put(ERROR_KEY, ErrorMsg.LACK_OF_PARAMETERS);
			return ERROR_PAGE;
		}
		map.put("mmsId", mmsId);
		FrameExample frameExample = new FrameExample();
		frameExample.createCriteria().andMmsIdEqualTo(mmsId);
		frameExample.setOrderByClause("sorting_num ASC");
		FrameDao frameDao = new FrameDao();
		List<Frame> frames = (List<Frame>) frameDao.select(frameExample);
		if (frames != null && frames.size() > 0)
			map.put("frame", frames.get(0));
		int totalFrame = frames.size();
		int currentFrame = totalFrame;
		if (totalFrame == 0)
			totalFrame = 1;
		if (totalFrame > 0)
			currentFrame = 1;
		map.put("currentFrame", currentFrame);
		map.put("totalFrame", totalFrame);
		return "forward:/module/frame/add.jsp";
	}
	
	@RequestMapping("/add.do")
	public String add(Frame frame, ModelMap map){
		if(frame == null){
			map.put(ERROR_KEY, ErrorMsg.NULL);
			return ERROR_PAGE;
		}else{
			try{
				FrameDao frameDao = new FrameDao();
				frameDao.insert(frame);
				return "forward:/module/frame/add.jsp";
			}catch(Exception e){
				map.put(ERROR_KEY, ErrorMsg.DAO_EXCEPTION);
				return ERROR_PAGE;
			}
		}
	}
	
	/**
	 * ajax方式编辑帧
	 * @param operate
	 * @param frame
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/ajaxOperate.do")
	@ResponseBody
	public Map<String, Object> ajaxOperate(Integer currentFrame, String operate, Frame frame){
		Map<String, Object> map = new HashMap<>();
		if(frame == null || operate == null){
			map.put(ERROR_KEY, ErrorMsg.NULL);
			map.put(AJAX_RESULT_KEY, AJAX_RESULT_FAIL);
			return map;
		}else{
			FrameExample frameExample = new FrameExample();
			frameExample.createCriteria().andMmsIdEqualTo(frame.getMmsId());
			try{
				FrameDao frameDao = new FrameDao();
				if("save".equals(operate)){
//					frameDao.insert(frame);
					MmsDao mmsDao = new MmsDao();
					Mms mms = (Mms) mmsDao.select(frame.getMmsId());
					if(mms != null){
						mms.setState(Constant.STATE_WAIT);
					}
//					mmsDao.update(mms);
					int totalFrame = frameDao.count(frameExample);
					map.put("totalFrame", totalFrame);
					map.put(AJAX_RESULT_KEY, AJAX_RESULT_SUCCESS);
				}else if ("insert".equals(operate)) {
					System.out.println(currentFrame);
					int totalFrame = frameDao.count(frameExample);
					if (currentFrame > totalFrame + 1) {
						currentFrame = totalFrame + 1;
					}
					frame.setSortingNum(currentFrame);
					if (frame.getId() == null)
						frameDao.insert(frame);
					else
						frameDao.update(frame);
					FrameExample notInsertAndSortingExample = new FrameExample();
					notInsertAndSortingExample.createCriteria().andMmsIdEqualTo(frame.getMmsId()).andIdNotEqualTo(frame.getId());
					notInsertAndSortingExample.setOrderByClause("sorting_num ASC");
					if (totalFrame > 0) {
						List<Frame> frames = (List<Frame>) frameDao.select(notInsertAndSortingExample);
						if (frames != null && frames.size() > 0) {
							for (int index = 0; index < frames.size(); index ++) {
								Frame f = frames.get(index);
								if (index + 1 < currentFrame && (index + 1) != f.getSortingNum()) {
									f.setSortingNum(index + 1);
								}
								if (index + 1 >= currentFrame && (index + 2) != f.getSortingNum()) {
									f.setSortingNum(index + 2);
									frameDao.updateByPrimaryKeySelective(f);
								}
							}
						}
					}
					MmsDao mmsDao = new MmsDao();
					Mms mms = (Mms) mmsDao.select(frame.getMmsId());
					if(mms != null){
						mms.setState(Constant.STATE_WAIT);
					}
					mmsDao.update(mms);
					totalFrame = frameDao.count(frameExample);
					map.put("frame", frame);
					map.put("totalFrame", totalFrame);
					map.put(AJAX_RESULT_KEY, AJAX_RESULT_SUCCESS);
				} else if ("next".equals(operate) || "previous".equals(operate)) {
					//TODO 需要判断值是否改变，来更新mms的状态字段。
					frame.setSortingNum(currentFrame);
					if (frame.getId() == null)
						frameDao.insert(frame);
					else
						frameDao.update(frame);
						
					int totalFrame = frameDao.count(frameExample);
					FrameExample notInsertAndSortingExample = new FrameExample();
					notInsertAndSortingExample.createCriteria().andMmsIdEqualTo(frame.getMmsId()).andIdNotEqualTo(frame.getId());
					notInsertAndSortingExample.setOrderByClause("sorting_num ASC");
					if (totalFrame > 0) {
						List<Frame> frames = (List<Frame>) frameDao.select(notInsertAndSortingExample);
						if (frames != null && frames.size() > 0) {
							for (int index = 0; index < frames.size(); index ++) {
								Frame f = frames.get(index);
								if (index + 1 < currentFrame && (index + 1) != f.getSortingNum()) {
									f.setSortingNum(index + 1);
								}
								if (index + 1 >= currentFrame && (index + 2) != f.getSortingNum()) {
									f.setSortingNum(index + 2);
									frameDao.updateByPrimaryKeySelective(f);
								}
							}
						}
					}
					
					totalFrame = frameDao.count(frameExample);
					if ("next".equals(operate))
						currentFrame += 1;
					else
						currentFrame -= 1;
					if (currentFrame < 1)
						currentFrame = 1;
					if (currentFrame > totalFrame)
						currentFrame = totalFrame;
					FrameExample example = new FrameExample();
					example.createCriteria().andMmsIdEqualTo(frame.getMmsId());
					example.setOrderByClause("sorting_num ASC");
					List<Frame> frames = (List<Frame>) frameDao.select(example);
					map.put("frame", frames.get(currentFrame - 1));
					map.put("currentFrame", currentFrame);
					map.put("totalFrame", totalFrame);
					map.put(AJAX_RESULT_KEY, AJAX_RESULT_SUCCESS);
				} else if ("delete".equals(operate)) {
					frameDao.delete(frame.getId());
					FrameExample example = new FrameExample();
					example.createCriteria().andMmsIdEqualTo(frame.getMmsId());
					example.setOrderByClause("sorting_num ASC");
					List<Frame> frames = (List<Frame>) frameDao.select(example);
					int totalFrame = frames.size() < 1 ? 1 : frames.size();
					currentFrame = currentFrame > 0 && currentFrame < totalFrame ? currentFrame : totalFrame;
					if (frames.size() > 0)
						map.put("frame", frames.get(currentFrame - 1));
					map.put("currentFrame", currentFrame);
					map.put("totalFrame", totalFrame);
					map.put(AJAX_RESULT_KEY, AJAX_RESULT_SUCCESS);
				}
				return map;
			}catch(Exception e){
				map.put(ERROR_KEY, ErrorMsg.DAO_EXCEPTION);
				return map;
			}
		}
	}
	
}
